<template>
  <client-only>
    <FormDialog :formOption="formOption" :form="form" :rule="rule" ref="dialogRef" :reload="reload"/>
  </client-only>
</template>

<script setup lang="ts">
import FormDialog from "~/components/common/FormDialog.vue";
import {
  useApi, useDepartmentTreeSelect
} from "~/composeables";
import {FormFieldType, FormOption} from "~/models/data/form";
import DepartmentCache from "~/store/system/departmentCache";

const props = defineProps<{
  reload: Function,
}>();


const api = useApi();

const dialogRef = ref<any>(null);

const onSubmit = (model: any) => {
  api.systemDepartmentApi.create(model)
      .then(res => {
        if (res.success) {
          ElMessage.success("提交数据成功！");
          forceReload();
        } else {
          ElMessage.error("数据提交失败,请重新尝试！");
        }
      })
      .catch(err => {
        console.error(err);
        ElMessage.error("数据提交失败");
      })
}

const formOption = ref<FormOption>({
  title: '录入单位信息',
  width: 480,
  labelWidth: 120,
  fieldList: [
    {
      fieldName: 'name',
      verboseName: '单位名称',
      fieldType: FormFieldType.input,
    },
    {
      fieldName: 'description',
      verboseName: '描述信息',
      fieldType: FormFieldType.textarea,
    },
    {
      fieldName: 'parentId',
      verboseName: '上级单位',
      fieldType: FormFieldType.cascader,
      selectSource: DepartmentCache.departmentTreeSelectSource,
      isMultiSelect: false,
    }
  ],
  submitFunc: onSubmit,
});

const form: any = ref({
  name: "",
  authors: "",
  publisher: "",
  pubDate: null,
  departmentId: null,
});

const rule = ref([]);

const open = () => {
  dialogRef.value.open();
}

const close = () => {
  dialogRef.value.close();
}

const forceReload = ()=>{
  window.location.reload()
}

defineExpose({
  open,
  close,
  dialogRef,
})

</script>